<template>
  <div class="forgot-password-page">
    <div class="forgot-password-container">
      <div class="forgot-password-form">
        <div class="form-header">
          <h2>重置密码</h2>
          <p>请输入您的邮箱地址，我们将发送验证码到您的邮箱</p>
        </div>

        <!-- 步骤指示器 -->
        <el-steps :active="currentStep" finish-status="success" align-center class="steps">
          <el-step title="验证邮箱" />
          <el-step title="重置密码" />
          <el-step title="完成" />
        </el-steps>

        <!-- 第一步：验证邮箱 -->
        <div v-if="currentStep === 0" class="step-content">
          <el-form
            ref="emailFormRef"
            :model="emailForm"
            :rules="emailRules"
            size="large"
          >
            <el-form-item prop="email">
              <el-input
                v-model="emailForm.email"
                placeholder="请输入邮箱地址"
                prefix-icon="Message"
                type="email"
              />
            </el-form-item>

            <el-form-item prop="code">
              <div class="code-input">
                <el-input
                  v-model="emailForm.code"
                  placeholder="请输入验证码"
                  prefix-icon="Key"
                />
                <el-button
                  type="primary"
                  :disabled="codeDisabled"
                  :loading="sendingCode"
                  @click="sendVerificationCode"
                >
                  {{ codeButtonText }}
                </el-button>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                class="submit-btn"
                :loading="verifying"
                @click="verifyCode"
              >
                {{ verifying ? '验证中...' : '验证邮箱' }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 第二步：重置密码 -->
        <div v-if="currentStep === 1" class="step-content">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            size="large"
          >
            <el-form-item prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>

            <el-form-item prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请确认新密码"
                prefix-icon="Lock"
                show-password
                @keyup.enter="resetPassword"
              />
            </el-form-item>

            <el-form-item>
              <div class="form-actions">
                <el-button @click="currentStep = 0">
                  上一步
                </el-button>
                <el-button
                  type="primary"
                  :loading="resetting"
                  @click="resetPassword"
                >
                  {{ resetting ? '重置中...' : '重置密码' }}
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>

        <!-- 第三步：完成 -->
        <div v-if="currentStep === 2" class="step-content success-content">
          <div class="success-icon">
            <el-icon size="60" color="#67C23A"><CircleCheck /></el-icon>
          </div>
          <h3>密码重置成功！</h3>
          <p>您的密码已成功重置，请使用新密码登录</p>
          <el-button type="primary" size="large" @click="goToLogin">
            立即登录
          </el-button>
        </div>

        <!-- 返回登录链接 -->
        <div v-if="currentStep < 2" class="back-to-login">
          <el-link type="primary" @click="goToLogin">
            返回登录
          </el-link>
        </div>
      </div>

      <div class="forgot-password-banner">
        <div class="banner-content">
          <h3>安全提示</h3>
          <p>为了保护您的账户安全，请确保：</p>
          <div class="security-tips">
            <div class="tip-item">
              <el-icon size="20"><Shield /></el-icon>
              <span>使用本人邮箱进行验证</span>
            </div>
            <div class="tip-item">
              <el-icon size="20"><Lock /></el-icon>
              <span>设置强密码组合</span>
            </div>
            <div class="tip-item">
              <el-icon size="20"><Hide /></el-icon>
              <span>不要泄露验证码信息</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sendPasswordResetCode, verifyPasswordResetCode, resetPasswordByCode } from '@/api/user'

const router = useRouter()

// 当前步骤
const currentStep = ref(0)

// 表单引用
const emailFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const sendingCode = ref(false)
const verifying = ref(false)
const resetting = ref(false)

// 验证码相关
const countdown = ref(0)
const codeDisabled = computed(() => countdown.value > 0)
const codeButtonText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}s后重发` : '发送验证码'
})

// 邮箱验证表单
const emailForm = reactive({
  email: '',
  code: ''
})

// 密码重置表单
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
})

// 邮箱验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ]
}

// 密码重置规则
const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-zA-Z])(?=.*\d)/, message: '密码必须包含字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validateField('email')
    sendingCode.value = true

    const response = await sendPasswordResetCode({ email: emailForm.email })
    
    if (response.code === 200) {
      ElMessage.success('验证码已发送到您的邮箱')
      startCountdown()
    } else {
      ElMessage.error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error('发送失败，请稍后重试')
  } finally {
    sendingCode.value = false
  }
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

// 验证邮箱验证码
const verifyCode = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validate()
    verifying.value = true

    const response = await verifyPasswordResetCode({
      email: emailForm.email,
      code: emailForm.code
    })

    if (response.code === 200) {
      ElMessage.success('验证成功')
      currentStep.value = 1
    } else {
      ElMessage.error(response.message || '验证失败')
    }
  } catch (error) {
    console.error('验证失败:', error)
    ElMessage.error('验证失败，请检查验证码')
  } finally {
    verifying.value = false
  }
}

// 重置密码
const resetPassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    resetting.value = true

    const response = await resetPasswordByCode({
      email: emailForm.email,
      code: emailForm.code,
      newPassword: passwordForm.newPassword
    })

    if (response.code === 200) {
      ElMessage.success('密码重置成功')
      currentStep.value = 2
    } else {
      ElMessage.error(response.message || '重置失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置失败，请稍后重试')
  } finally {
    resetting.value = false
  }
}

// 返回登录页面
const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.forgot-password-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.forgot-password-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  max-width: 1000px;
  width: 100%;
  min-height: 600px;
}

.forgot-password-form {
  flex: 1;
  padding: 60px 50px;
  display: flex;
  flex-direction: column;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  color: #303133;
  margin-bottom: 8px;
  font-size: 28px;
}

.form-header p {
  color: #909399;
  font-size: 16px;
  line-height: 1.6;
}

.steps {
  margin-bottom: 40px;
}

.step-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.code-input {
  display: flex;
  gap: 12px;
}

.code-input .el-input {
  flex: 1;
}

.code-input .el-button {
  width: 120px;
  flex-shrink: 0;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.form-actions {
  display: flex;
  gap: 16px;
  width: 100%;
}

.form-actions .el-button {
  flex: 1;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.success-content {
  text-align: center;
  padding: 40px 0;
}

.success-icon {
  margin-bottom: 24px;
}

.success-content h3 {
  color: #303133;
  font-size: 24px;
  margin-bottom: 16px;
}

.success-content p {
  color: #909399;
  font-size: 16px;
  margin-bottom: 32px;
  line-height: 1.6;
}

.back-to-login {
  text-align: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.forgot-password-banner {
  flex: 1;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  position: relative;
}

.banner-content {
  text-align: center;
  padding: 40px;
  max-width: 400px;
}

.banner-content h3 {
  font-size: 28px;
  margin-bottom: 16px;
  font-weight: 600;
}

.banner-content p {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 32px;
  line-height: 1.6;
}

.security-tips {
  display: flex;
  flex-direction: column;
  gap: 20px;
  text-align: left;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  backdrop-filter: blur(10px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .forgot-password-container {
    flex-direction: column;
    margin: 20px;
  }
  
  .forgot-password-form {
    padding: 40px 30px;
  }
  
  .forgot-password-banner {
    min-height: 200px;
  }
  
  .banner-content {
    padding: 20px;
  }
  
  .security-tips {
    gap: 12px;
  }
  
  .tip-item {
    padding: 8px;
    font-size: 14px;
  }
  
  .code-input {
    flex-direction: column;
    gap: 12px;
  }
  
  .code-input .el-button {
    width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>